<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/11
 */
namespace base\model;
use think\Validate;

trait ModelTrait
{
	
	//错误信息
    private  $curlError;
	
	/**
     * 获取错误
     * @return type
    */
    public function  getError(){
    	return $this -> errorInfo ?: $this->curlError;
    }
	
	/**
     * 获取列表
     * @return type
     */
	public function getList($where,$pageIndex=0,$pageSize=20)
    {
    	$model = new self;
    	$fields = $model -> fields;
		$model = $model->where($where);
		if($fields){
			$model = $model->field($fields);
		}else{
			$model = $model->field("is_del",true);
		}
		if($pageIndex>0){
			$model = $model->page($pageIndex,$pageSize);
		}
		return $model->select();
    }
	
	/**
     * 详情
     * @return type
     */
	public function details($id,$fields='')
    {
    	if(empty($fields)){
    		return self::get($id);
    	}else{
    		return self::field($fields)->get($id);
    	}
    }
    
	/**
     * 添加
     * @param type $data
     * @return type
     */
	public function add($data)
    {
    	$validate = new Validate;
		$validate->rule( $this->rule ?? [] );
        if( !$validate->check($data) ) {
        	$this -> errorInfo = $this->curlError  = $validate->getError();
            return false;
        }
    	self::allowField(true)->save($data);
		return $this;
    }
    
	/**
     * 编辑
     * @param type $data
     * @return type
     */
	public function edit($data)
    {
		$this->rule['id'] =  'require|integer';
    	$validate = new Validate;
		$validate->rule($this->rule);
        if( !$validate->check($data) ) {
        	$this -> errorInfo = $validate->getError();
            return false;
        }
    	self::allowField(true)->isUpdate(true) -> save($data);
		return $this;
    }
	
	/**
     * 删除
     * @param type $id
     * @return type
     */
	public function del($id)
    {
    	return self::where('id',$id) ->delete();
    }
	
	/**
     * 移除
     * @param type $id
     * @return type
     */
	public function remove($id)
    {
    	return self::where('id',$id)->update(['is_del'=>1]);
    }
}